#抓取https://test.f66b88sport.com/pc/index.html#/
import time

import requests

import random

from pb.comfuc import Comfuc
from pb.ref import Ref
from pb.sport import Sport
import logging

class GetFBodds:

    def fetch_match_list(self):

        url = "https://sportapi.fastball2.com/v1/match/getList"


        User_Agent_list = [
            {
                'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 Edg/126.0.0.0'
            }, {
                'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36'
            }
        ]

        User_Agent = random.choice(User_Agent_list)

        # 请求头
        headers =  {
            "Accept": "application/json, text/plain, */*",
            "Accept-Encoding": "gzip, deflate, br, zstd",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "Connection": "keep-alive",
            "Content-Type": "application/json;charset=UTF-8",
            "Content-Length":"22",
            "Host": "sportapi.fastball2.com",
            "Origin": "https://test.f66b88sport.com",
            "Referer": "https://test.f66b88sport.com/",
            "Sec-Fetch-Dest": "empty",
            "Sec-Fetch-Mode": "cors",
            "Sec-Fetch-Site": "cross-site",
            "Sec-Ch-Ua-mobile": "?0",
            "Sec-Ch-Ua-platform": '"Windows"'
        }
        headers['User-Agent'] = User_Agent.get('user-agent')
        headers['Sec-Ch-Ua'] =  '"Not/A)Brand";v="8", "Chromium";v="126", "Microsoft Edge";v="126"'
        # 更新后的请求体 (payload)
        payload = {
            "languageType": 'ENG',#CMN or ENG
            "current": 1,
            "orderBy": 0,
            "isPC": True,
            "type": 3, #3早盘
            "sportId":1
        }

        try:
            # 发起 POST 请求
            session = requests.Session()
            response = session.post(url, headers=headers, json=payload, timeout=10)

            # 检查响应状态码
            if response.status_code == 200:
                session.close()
               # print("请求成功，返回的数据如下：")
                #print(response.json() )  # 输出 JSON 数据
                return response.json()

            else:
                logging.warning(f"请求失败，状态码：{response.status_code}")
                logging.warning("响应内容：", response.text)
        except Exception as e:
            logging.error(f"请求过程中发生错误：{e}")
            time.sleep(6)


    def getList(self):
        sports = []
        list = self.fetch_match_list()
        if list is None:
            time.sleep(2)
            return
        for fbdata in list['data']['records']:
            match = fbdata.get('nm')

            teams = match.split(" vs ")
            lsname = fbdata['lg']['na']
            sport = Sport(teams[0], teams[1], lsname)
            sport.sport_id = fbdata['id']
            sport.start_time = fbdata['bt']
            for pk in fbdata['mg']:
                # rg = ['让球','大/小']
                rg = ['Handicap', 'Over/Under']
                if pk['nm'] == rg[0]:
                    for some in pk['mks']:
                        sport.full_hdp_odd[float(some['li'])] = [some['op'][0]['od'], some['op'][1]['od']]
                if pk['nm'] == rg[1]:
                    for some in pk['mks']:
                        sport.full_ou_odd[float(some['li'])] = [some['op'][0]['od'], some['op'][1]['od']]
            if len(sport.full_hdp_odd) == 0:
                continue
            odds = next(iter(sport.full_hdp_odd.values()))
            return_rate = Comfuc.calculate_return_rate(odds[0], odds[1])
            if sport.start_time/1000-time.time()<3600 and return_rate>96.6:
                sport.return_rate = return_rate
                sports.append(sport)
        return sports

if __name__ == "__main__":
    getFBodds = GetFBodds()
    sports = []
    list = getFBodds.fetch_match_list()

    for fbdata in list['data']['records']:
        match = fbdata.get('nm')

        teams = match.split(" vs ")
        lsname = fbdata['lg']['na']
        sport = Sport(teams[0], teams[1], lsname)
        sport.sport_id = fbdata['id']
        sport.start_time = fbdata['bt']
        print(sport)
        for pk in fbdata['mg']:
            #rg = ['让球','大/小']
            rg = ['Handicap','Over/Under']
            if pk['nm'] == rg[0]:
                for some in pk['mks']:
                    sport.full_hdp_odd[float(some['li'])] = [some['op'][0]['od'], some['op'][1]['od']]
                print(sport.full_hdp_odd)
            if pk['nm'] == rg[1]:
                for some in pk['mks']:
                    sport.full_ou_odd[float(some['li'])] = [some['op'][0]['od'], some['op'][1]['od']]
                print(sport.full_ou_odd)
        #print(sport)
        if len(sport.full_hdp_odd)==0:
            continue
        odds = next(iter(sport.full_hdp_odd.values()))
        if sport.start_time/1000-time.time()<3600  and ( Comfuc.calculate_return_rate(odds[0],odds[1])>97):
            sports.append(sport)
    print(len(sports))
    #print(1111111111)
    for s in sports:
        print(s)